import 'package:boss/models/material.dart' as material;
import 'package:boss/models/store_menu.dart';
import 'package:boss/ui/page/commodity/categories/page/plusCommodityMode/page/plusCommodityByFormField/page/materialSetting/model/commodity_material.dart';

import 'package:hi_common/hi_common.dart';
import 'package:flutter/material.dart';

class MaterialSettingProvider extends ChangeNotifier {
  StoreMenu menu;

  List<material.Material> get menuMaterials => menu.commodityMeterialList;
  List<CommodityMaterial> commodityMaterials;

  int meterialType;

  MaterialSettingProvider({
    StoreMenu menu,
    List<material.Material> commodityMaterials,
    this.meterialType = 0,
  }) {
    this.menu = StoreMenu.fromJson(menu.toJson());

    if (meterialType == 0) {
      this.commodityMaterials = commodityMaterials.map((item) {
        var newOne = CommodityMaterial(
            name: item.meterialName,
            price: AmountUtil.price2String(item.meterialPrice));

        return newOne;
      }).toList();

      this.menu.commodityMeterialList = commodityMaterials;
    } else {
      this.commodityMaterials = commodityMaterials.map((item) {
        var newOne = CommodityMaterial(
            name: item.meterialName,
            price: AmountUtil.price2String(item.meterialPrice));

        return newOne;
      }).toList();
    }
  }

  addCommodityMaterials() {
    var newMaterial = material.Material.fromJson({});
    newMaterial.meterialPrice = null;
    commodityMaterials.add(CommodityMaterial());
    notifyListeners();
  }

  removeCommodityMaterials(CommodityMaterial material) {
    commodityMaterials.remove(material);
    notifyListeners();
  }

  setTabIndex(int index) {
    meterialType = index;
    notifyListeners();
  }

  saveAndPop(BuildContext context) {
    if (meterialType == 0) {
      Navigator.pop(context, {
        'meterials': menuMaterials,
        'meterialType': meterialType,
      });
    } else {
      var flag = commodityMaterials.every((item) {
        if (item.name == '') {
          return false;
        }

        if (!RegUtil.testPrice(item.price)) {
          return false;
        }

        return true;
      });

      if (!flag) {
        toast('请检查加料名称或价钱是否完整或格式正确');
        return;
      }

      Navigator.pop(
          context,
          {
            'meterials': commodityMaterials
                .map((item) => material.Material.fromJson({
              'meterialName': item.name,
              'meterialPrice': AmountUtil.string2Price(item.price),
            })).toList(),
            'meterialType': meterialType,
          });
    }
  }

  setMenuMaterial(List<material.Material> materials) {
    menu.commodityMeterialList = materials;
    notifyListeners();
  }
}
